package ctm.javacode;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import javax.imageio.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/AuthImage.do") 

public class authImage extends HttpServlet {
	
	private int colorR ;
	private int colorG ;
	private int colorB ;
	
	public Color RandColor(int arg1, int arg2 ) {
	    Random random = new Random();
		colorR = arg1 + random.nextInt(arg2-arg1);
		colorG = arg1 + random.nextInt(arg2-arg1);
		colorB = arg1 + random.nextInt(arg2-arg1);
		return new Color(colorR, colorG, colorB) ;
	} // end RandColor()
	
	protected void doGet( HttpServletRequest request,
								HttpServletResponse response ) throws ServletException, IOException {
		
		
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		HttpSession session = request.getSession();
		
		
		int width = 60 ;
		int height = 20 ;
		BufferedImage image = new BufferedImage(
					width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graph = image.getGraphics();
		Random random = new Random();
		graph.setColor(RandColor(200,250));
		graph.fillRect(0, 0, width, height);
		graph.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		
		graph.setColor(RandColor(160,200)); //乾擾線顏色
		
		for (int i=0; i<155; i++) { // 155條干擾線
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			graph.drawLine(x, y, x+xl, y+yl);
		} // end for
		
		//-以下取隨機4碼數字
		String sRand="";
		for(int i=0;i<4;i++) {
			String rand=String.valueOf(random.nextInt(10));
		    sRand+=rand;
		    // 將認證碼顯示到圖像中
		    graph.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
		    graph.drawString(rand,13*i+6,16);
		} // end for
		graph.dispose();
		
		session.setAttribute("AuthCode", sRand);
		ImageIO.write(image, "JPEG", response.getOutputStream());
		
	} // end CreateImage()

}
